import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../common/extension/string_extension.dart';
import '../common/api_service.dart';
import '../common/routes.dart';
import '../model/user_model.dart';

class UserListView extends StatefulWidget {
  final String searchText;

  const UserListView({super.key, required this.searchText});

  @override
  State<UserListView> createState() => _UserListViewState();
}

class _UserListViewState extends State<UserListView> {
  final List<UserModel> _userList = [];

  @override
  void initState() {
    super.initState();

    _searchUserList();
  }

  void _searchUserList() {
    ApiService().searchUserList(widget.searchText, 1, (list) {
      setState(() {
        _userList.clear();
        _userList.addAll(list);
      });
    }, () {});
  }

  Widget _buildListViewItem(BuildContext context, int index) {
    var user = _userList[index];
    var avatar = user.avatar ?? "";
    avatar = avatar.getThumbUrl(size: 200);
    final num = "${user.cartoonCount ?? 0}角色 ${user.pipeCount ?? 0}内容";

    return Padding(
      padding: const EdgeInsets.fromLTRB(10, 8, 10, 8),
      child: Container(
        decoration: const BoxDecoration(
          color: Colors.white,
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            ClipRRect(
                borderRadius: BorderRadius.circular(22),
                child: CachedNetworkImage(
                  fit: BoxFit.cover,
                  fadeInDuration: const Duration(milliseconds: 100),
                  fadeOutDuration: const Duration(seconds: 0),
                  imageUrl: avatar,
                  width: 44,
                  height: 44,
                )),
            const SizedBox(width: 10),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    user.nickname ?? "",
                    overflow: TextOverflow.ellipsis,
                    maxLines: 1,
                    style: const TextStyle(fontSize: 15, fontWeight: FontWeight.bold),
                  ),
                  Text(
                    num,
                    style: const TextStyle(color: Colors.black45),
                  )
                ],
              ),
            ),
            FilledButton(
                onPressed: () {
                  Get.toNamed(Routes.PROFILE, arguments: {"uid": user.uid});
                },
                style: FilledButton.styleFrom(minimumSize: Size.zero, padding: const EdgeInsets.fromLTRB(12, 5, 12, 7)),
                child: const Text("个人主页", style: TextStyle(fontSize: 13)))
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(itemCount: _userList.length, itemBuilder: _buildListViewItem);
  }
}
